<template>
  <div>
    <a-table :columns="columns" :data-source="editableData" :pagination="false" row-key="key">
      <template slot="buildProportion" slot-scope="text, record, index">
        <div v-if="isEditing">
          <a-tooltip title="数值范围为[0,100]">
            <a-input-number
              :value="record.buildProportion"
              :min="0"
              :max="100"
              :precision="2"
              :formatter="value => `${value}%`"
              :parser="value => value.replace('%', '')"
              style="width: 100%"
              @change="value => handleProportionChange(index, value)"
            />
          </a-tooltip>
        </div>
        <span v-else>{{ parseFloat(text || 0).toFixed(2) }}%</span>
      </template>
    </a-table>
    <div v-if="isEditing" style="margin-top: 16px; text-align: right;">
      <a-button @click="cancelEdit" style="margin-right: 8px;">
        取消
      </a-button>
      <a-button type="primary" @click="saveChanges" :disabled="totalError">
        保存
      </a-button>
      <div v-if="totalError" style="color: red; margin-top: 8px; text-align: left;">
        总占比不能超过100%，当前总计：{{ totalProportion.toFixed(2) }}%
      </div>
    </div>
  </div>
</template>

<script>
export default {
  props: {
    data: {
      type: Array,
      default: () => [],
    },
    isEditing: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      editableData: [],
      originalData: [],
      columns: [
        {
          title: '分箱编号',
          dataIndex: 'key',
          key: 'key',
        },
        {
          title: '分箱类型',
          dataIndex: 'binType',
          key: 'binType',
          customRender: (text) => {
            return '数值区间'
          },
        },
        {
          title: '数值',
          dataIndex: 'binRuleDetails',
          key: 'binRuleDetails',
        },
        {
          title: '建模时占比',
          dataIndex: 'buildProportion',
          key: 'buildProportion',
          scopedSlots: { customRender: 'buildProportion' },
        },
      ],
    }
  },
  computed: {
    totalProportion() {
      return this.editableData.reduce((sum, item) => {
        return sum + (parseFloat(item.buildProportion) || 0)
      }, 0)
    },
    totalError() {
      return this.totalProportion > 100
    },
  },
  watch: {
    data: {
      handler(newData) {
        console.log('newData----', newData)
        this.initData(newData)
      },
      immediate: true,
      deep: true
    },
    isEditing: {
      handler(newVal) {
        if (!newVal) {
          // 当编辑状态变为false时，恢复原始数据
          this.editableData = JSON.parse(JSON.stringify(this.originalData))
        }
      }
    }
  },
  methods: {
    initData(data) {
      if (Array.isArray(data)) {
        this.editableData = data.map(item => ({ ...item }))
      } else {
        this.editableData = []
      }
      this.originalData = JSON.parse(JSON.stringify(this.editableData))
    },
    cancelEdit() {
      this.editableData = JSON.parse(JSON.stringify(this.originalData))
      this.$emit('cancel-edit')
    },
    handleProportionChange(index, value) {
      if (value !== null && value !== undefined) {
        this.$set(this.editableData[index], 'buildProportion', value)
      }
    },
    saveChanges() {
      if (this.totalError) {
        this.$message.error('总占比不能超过100%，请调整后再保存')
        return
      }
      // 触发父组件事件，传递修改后的数据
      this.$emit('data-changed', this.editableData)
      this.originalData = JSON.parse(JSON.stringify(this.editableData))
      this.$message.success('保存成功')
    }
  }
}
</script>

<style lang="less" scoped>
.ant-input-number {
  width: 100%;
}
</style>
